package view;

import Parmcfg.DevManager;
import Parmcfg.TestDemo;
import util.LogManager;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ScanCameraFrame extends JFrame {

    private JTextArea logArea;
    private PlaceholderTextField ipField, accountField, passwordField, channelField, timesField;
    private boolean started = false;
    private final ExecutorService executorService = Executors.newFixedThreadPool(4); // 线程池
    private JButton connectButton;

    public ScanCameraFrame() {
        setTitle("海康网络sdk工具");
        setSize(720, 480);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new GridLayout(1, 2));

        JPanel cameraPanel = createCameraPanel();
        JPanel logPanel = createLogPanel();

        add(cameraPanel);
        add(logPanel);
    }

    private JPanel createCameraPanel() {
        JPanel cameraPanel = new JPanel();
        cameraPanel.setLayout(new BoxLayout(cameraPanel, BoxLayout.Y_AXIS));
        cameraPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JLabel titleLabel = new JLabel("camera configuration");
        titleLabel.setFont(new Font("Arial", Font.BOLD, 18));
        titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        cameraPanel.add(titleLabel);
        cameraPanel.add(Box.createRigidArea(new Dimension(0, 20)));

        JPanel inputPanel = createInputPanel();
        cameraPanel.add(inputPanel);
        cameraPanel.add(Box.createRigidArea(new Dimension(0, 20)));

        connectButton = new JButton("start run");
        connectButton.setFont(new Font("Arial", Font.BOLD, 14));
        connectButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        connectButton.addActionListener(e -> startExecution());
        cameraPanel.add(connectButton);

        return cameraPanel;
    }

    private JPanel createInputPanel() {
        JPanel inputPanel = new JPanel(new GridBagLayout());
        inputPanel.setOpaque(false);
        inputPanel.setBackground(new Color(255, 255, 255, 128));
        inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(5, 5, 5, 5);

        ipField = new PlaceholderTextField("10.60.4.65");
        styleTextField(ipField);
        addInputField(inputPanel, "IP 地址:", ipField, gbc, 0);

        accountField = new PlaceholderTextField("admin");
        styleTextField(accountField);
        addInputField(inputPanel, "账号:", accountField, gbc, 1);
        accountField.setText("admin");

        passwordField = new PlaceholderTextField("xyy123456");
        styleTextField(passwordField);
        addInputField(inputPanel, "密码:", passwordField, gbc, 2);
        passwordField.setText("fd123456");

        channelField = new PlaceholderTextField("1");
        styleTextField(channelField);
        addInputField(inputPanel, "通道号:", channelField, gbc, 3);
        channelField.setText("1");

        timesField = new PlaceholderTextField("20");
        styleTextField(timesField);
        addInputField(inputPanel, "执行次数:", timesField, gbc, 4);
        timesField.setText("100");

        return inputPanel;
    }

    private JPanel createLogPanel() {
        JPanel logPanel = new JPanel(new BorderLayout());
        logArea = new JTextArea();
        logArea.setFont(new Font("Monospaced", Font.PLAIN, 14));
        logArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(logArea);
        logPanel.add(scrollPane, BorderLayout.CENTER);
        return logPanel;
    }

    private void startExecution() {
        if (started) {
            JOptionPane.showMessageDialog(this, "程序执行中...", "温馨提示", JOptionPane.ERROR_MESSAGE);
            return;
        }
        started = true;
        connectButton.setText("starting");

        executorService.submit(this::executeTasks);
    }

    private void executeTasks() {
        try {
            String ips = ipField.getText().trim();
            String account = accountField.getText().trim();
            String password = passwordField.getText().trim();
            int times = Integer.parseInt(timesField.getText().trim());

            boolean sdkLoaded = TestDemo.createSDKInstance();
            LogManager.getInstance().appendLog("加载sdk" + (sdkLoaded ? "成功!" : "失败!"), this);

            String[] ipList = ips.contains(";") ? ips.split(";") : new String[]{ips};

            for (int j = 0; j < times; j++) {
                LogManager.getInstance().appendLog("开始执行第【" + (j + 1) + "】次！", this);
                for (String ip : ipList) {
                    try {
                        LogManager.getInstance().appendLog("开始执行: " + ip, this);
                        int lUserID = TestDemo.loginDevice(ip, (short) 8000, account, password);
                        if (lUserID != -1) {
                            try {
                                DevManager.getDeviceStatus(lUserID);
                                DevManager.getDeviceInfo(lUserID);
                                DevManager.getPresetList(lUserID);
                                DevManager.getPtzPosition(lUserID);
                                TestDemo.logout(lUserID);
                            } catch (Exception e) {
                                System.out.println(e.getMessage());
                            }
                        }
                    } catch (Exception ex) {
                        LogManager.getInstance().appendLog("执行过程中断：" + ex.getMessage());
                    }
                }
                LogManager.getInstance().appendLog("第【" + (j + 1) + "】次执行完毕！", this);
            }
        } finally {
            SwingUtilities.invokeLater(() -> {
                started = false;
                connectButton.setText("start run");
                LogManager.getInstance().shutdown();
            });
        }
    }

    private void addInputField(JPanel panel, String labelText, JTextField textField, GridBagConstraints gbc, int row) {
        gbc.gridx = 0;
        gbc.gridy = row;
        panel.add(new JLabel(labelText), gbc);
        gbc.gridx = 1;
        gbc.weightx = 1.0;
        panel.add(textField, gbc);
    }

    private void styleTextField(JTextField textField) {
        textField.setPreferredSize(new Dimension(200, 30));
        textField.setBorder(new LineBorder(Color.GRAY, 1, true));
        textField.setMargin(new Insets(8, 8, 8, 8));
    }

    static class PlaceholderTextField extends JTextField {
        private final String placeholder;

        public PlaceholderTextField(String placeholder) {
            this.placeholder = placeholder;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (getText().isEmpty()) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setColor(Color.LIGHT_GRAY);
                g2.setFont(getFont().deriveFont(Font.ITALIC));
                g2.drawString(placeholder, 8, getHeight() / 2 + 5);
            }
        }
    }

    public void showBoard(String msg) {
        if (logArea != null) {
            try {
                logArea.append(msg + "\n"); // 添加新日志
                logArea.setCaretPosition(logArea.getDocument().getLength()); // 自动滚动到最后
                if (logArea.getLineCount() > 100) { // 如果超过100条日志，删除第一条
                    try {
                        int endOfFirstLine = logArea.getLineEndOffset(0);
                        logArea.replaceRange("", 0, endOfFirstLine); // 删除第一条日志
                    } catch (Exception e) {
                        System.out.println("删除日志失败：" + e.getMessage());
                    }
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
}
